package db.nio.handler;

import db.nio.ChannelContext;
import db.nio.Processor;

import java.nio.channels.SelectionKey;
import java.util.List;

/**
 * 员工工作流水(数据读取线程)
 * Created by daibin on 10/27/16.
 */
public class BackHandler implements Runnable {

    /**
     * 需求事件
     */
    public SelectionKey selectionKey;


    /**
     *
     * @param selectionKey 触发事件
     */
    public BackHandler(SelectionKey selectionKey){
        this.selectionKey = selectionKey;
    }

    @Override
    public void run() {
        //通道信息
        ChannelContext context = (ChannelContext) selectionKey.attachment();

        //处理器
        Processor processor = context.getProcessor();
        try {
            List<Object> objectList = context.read();
            if (objectList != null) {
                for(Object object:objectList) {
                    try {
                        processor.doProcessor(object, context);
                    } catch (Exception e) {
                        processor.doException(e,context);
                    }
                }
            }
        } finally {
            if (selectionKey.isValid())
                selectionKey.interestOps(SelectionKey.OP_READ);
        }
    }
}
